package com.ruoyi.shop.common.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtils {

    /**
     * 根据 IP 地址查询用户所在城市
     *
     * @param ip IP 地址
     * @return 城市名称
     */
    public static String getCityByIP(String ip) {
        String city = "";
        try {
            // 构造查询 URL
            String urlString = "http://whois.pconline.com.cn/ipJson.jsp?ip=" + ip;
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 发送请求并获取响应结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("GBK")));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 使用正则表达式从响应内容中提取城市信息
            String regex = "\"city\":\"([^\"]+)\"";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(response.toString());
            if (matcher.find()) {
                city = matcher.group(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return city;
    }

    public static void main(String[] args) {
        String ip = "117.187.228.117"; // 实际的IP地址
//        String ip = "120.36.213.176"; // 实际的IP地址
        String city = IPUtils.getCityByIP(ip);
        System.out.println("ip(" + ip + ")所在的城市为:" + city);

    }
}

